package demoflink.window;

import demoflink.entity.WaterSensor;
import demoflink.function.WaterSensorMapFunction;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.GlobalWindows;
import org.apache.flink.streaming.api.windowing.assigners.ProcessingTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.assigners.SlidingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

public class WindowApiDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());
        KafkaSource<String> kafkaSource = KafkaSource.<String>builder()
                .setBootstrapServers("node1:9092,node2:9092,node3:9092")
                .setGroupId("local")
                .setTopics("first")
                .setValueOnlyDeserializer(new SimpleStringSchema())
                .setStartingOffsets(OffsetsInitializer.latest())
                .build();
        SingleOutputStreamOperator<WaterSensor> source = env.fromSource(kafkaSource, WatermarkStrategy.noWatermarks(), "kafkaSource").map(new WaterSensorMapFunction());
        //并行度为1 source没有keyby
        //source.windowAll()
        KeyedStream<WaterSensor, String> keyedStream = source.keyBy(waterSensor -> waterSensor.getId());

        //TODO 1.指定窗口分配器 指定用哪一种窗口 时间or计数 滚动\滑动\会话
        //基于时间的

        //滚动窗口
        //WindowedStream<WaterSensor, String, TimeWindow> window = keyedStream.window(TumblingProcessingTimeWindows.of(Time.seconds(10)));
        //滑动窗口
        //keyedStream.window(SlidingProcessingTimeWindows.of(Time.seconds(10),Time.seconds(2)));
        //会话窗口 间隔多久没有新的数据来 将之前的进行统计
        //keyedStream.window(ProcessingTimeSessionWindows.withGap(Time.seconds(10)));

        //基于计数

        //滚动窗口
        //keyedStream.countWindow(5);
        //滑动窗口
        keyedStream.countWindow(5,2);

        //全局窗口
        //keyedStream.window(GlobalWindows.create());



        env.execute();

    }
}
